package com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.question.TikuImgUploadReqModel;
import com.china08.yxyapi.model.question.TikuImgUploadRespModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 作业系统相关的上传试题
 * 
 * @author tyw
 *
 */
@CrossOrigin
@Controller
@RequestMapping(value = "/api_yw/manage/tec/homework/question")
public class UploadConfigController extends YxyApiBaseController {

    private final Logger LOGGER = LoggerFactory.getLogger(UploadConfigController.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${yx.tiku.img.upload.url}")
    private String url = "";

    @RequestMapping(value = "/ueserver", method = RequestMethod.GET)
    @ResponseBody
    public Object ueserver(HttpServletRequest request, HttpServletResponse response, @Param("action") String action) {
        Map<String, Object> jsonObject;
        ObjectMapper objectMapper;
        try {
            jsonObject = new HashMap<>();
            objectMapper = new ObjectMapper();
            System.out.println("ueserver is ok.");
            System.out.println("action is " + action);
            // 需要支持callback参数,返回jsonp格式
            // {
            // "imageUrl":
            // "http://localhost/ueditor/php/controller.php?action=uploadimage",
            // "imagePath": "/ueditor/php/",
            // "imageFieldName": "upfile",
            // "imageMaxSize": 2048,
            // "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
            // }
            jsonObject.put("imageUrl", "/homework/teacher/upload/ueserver");
            jsonObject.put("imageUrlPrefix", "");
            jsonObject.put("imagePath", "/homework/teacher/upload/ueserver");
            jsonObject.put("imageFieldName", "upfile");
            jsonObject.put("scrawlFieldName", "scrawlFieldName");
            jsonObject.put("imageActionName", "uploadscrawl");
            jsonObject.put("imageMaxSize", "512000");
            jsonObject.put("imageAllowFiles", new String[] { ".png", ".jpg", ".jpeg", ".gif" });
            return objectMapper.writeValueAsString(jsonObject);
        } catch (Exception e) {
            LOGGER.error("图片服务器配置异常", e);
        }
        return "";
    }

    @RequestMapping(value = "/ueserver", method = RequestMethod.POST)
    @ResponseBody
    public String base64(@RequestParam(name = "scrawlFieldName", required = false) String base64,
            @RequestParam("action") String action, HttpServletRequest rq, HttpServletResponse rp)
                    throws JsonProcessingException {
        Map<String, String> jsonObject = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        jsonObject.put("state", "error");
        jsonObject.put("url", "");
        jsonObject.put("title", "title");
        jsonObject.put("original", "fromBase64");
        try {
            System.out.println("base64img server is ok.");
            System.out.println("action is " + action);

            TikuImgUploadReqModel request = new TikuImgUploadReqModel();
            byte[] b = Base64.decodeBase64(base64);
            String content = Base64.encodeBase64String(b);
            String md5 = DigestUtils.md5Hex(b);
            request.setContent(content);
            request.setMd5(md5);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<TikuImgUploadReqModel> requestEntity = new HttpEntity<>(request, headers);
            TikuImgUploadRespModel respModel = restTemplate.postForObject(url, requestEntity,
                    TikuImgUploadRespModel.class);

            jsonObject.put("state", "SUCCESS");
            jsonObject.put("url", respModel.getFullPath());
            jsonObject.put("title", "title");
            jsonObject.put("original", "fromBase64");
            System.out.println(objectMapper.writeValueAsString(jsonObject));
            return objectMapper.writeValueAsString(jsonObject);
        } catch (Exception e) {
            LOGGER.error("作业系统上传公式图片异常！", e);
        }
        return objectMapper.writeValueAsString(jsonObject);

    }

    @RequestMapping(value = "/ueserver", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public String uploadimage(@RequestParam("upfile") MultipartFile file, @RequestParam("action") String action,
            HttpServletRequest rq, HttpServletResponse rp) {
        Map<String, String> jsonObject = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            System.out.println("uploadimage server is ok.");
            System.out.println("action is " + action);

            TikuImgUploadReqModel request = new TikuImgUploadReqModel();
            byte[] b = file.getBytes();
            String content = Base64.encodeBase64String(b);
            String md5 = DigestUtils.md5Hex(b);
            request.setContent(content);
            request.setMd5(md5);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<TikuImgUploadReqModel> requestEntity = new HttpEntity<>(request, headers);
            TikuImgUploadRespModel respModel = restTemplate.postForObject(url, requestEntity,
                    TikuImgUploadRespModel.class);

            if ("0".equals(respModel.getEvent())) {
                jsonObject.put("state", "SUCCESS");
                jsonObject.put("url", respModel.getFullPath());
                jsonObject.put("title", file.getOriginalFilename());
                jsonObject.put("original", "fromuploadimage");
            } else {
                jsonObject.put("state", "服务器异常");
                jsonObject.put("url", respModel.getFullPath());
                jsonObject.put("title", file.getOriginalFilename());
                jsonObject.put("original", "fromuploadimage");
            }

            System.out.println(objectMapper.writeValueAsString(jsonObject));
            return objectMapper.writeValueAsString(jsonObject);
        } catch (Exception e) {
            LOGGER.error("作业系统上传图片异常！", e);
        }
        return "";
    }
}
